package com.kingdee.pda.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.basecommon.utils.SpeakUtils;
import com.kingdee.pda.R;
import com.kingdee.pda.adapter.GoodsLocationsAdapter;
import com.kingdee.pda.entity.Warehouse;
import com.kingdee.pda.entity.WarehouseLocation;
import com.kingdee.pda.plugins.http.common.OnRequestCallback;
import com.kingdee.pda.plugins.http.serverinterface.IQueryGoodsLocation;
import com.kingdee.pda.plugins.http.serverinterface.impl.QueryGoodsLocationImpl;
import com.kingdee.pda.util.CommonUtil;
import com.kingdee.pda.util.GlideUtils;
import com.kingdee.pda.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品库位查询
 * Created by zhanlg
 * DATE 2021/5/26
 * TIME 9:37
 */
public class QueryGoodsLocationActivity extends BaseTitleActivity {

    private ImageView mIvGoodsPic;
    private TextView mTvGoodsName;
    private TextView mTvSpecName;
    private TextView mTvSKUNum;
    private TextView mTvGoodsNum;
    private TextView mTvGoodsBarcode;
    private TextView mTvNoDataTips;
    private ListView mListView;
    private IQueryGoodsLocation mIQueryGoodsLocation;
    private GoodsLocationsAdapter mAdapter;
    private EditText et_skuCode;

    public static void actionStart(Context context) {
        context.startActivity(new Intent(context, QueryGoodsLocationActivity.class));
    }

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        super.onActivityCreate(savedInstanceState);
        setContentView(R.layout.activity_query_goods_location);
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("商品库位查询");
        mIvGoodsPic = findViewById(R.id.iv_goods_pic);
        mTvGoodsName = findViewById(R.id.tv_goods_name);
        mTvSpecName = findViewById(R.id.tv_spec_name);
        mTvSKUNum = findViewById(R.id.tv_sku_num);
        mTvGoodsNum = findViewById(R.id.tv_goods_num);
        mTvGoodsBarcode = findViewById(R.id.tv_goods_barcode);
        mTvNoDataTips = findViewById(R.id.tv_no_data_tips);
        mListView = findViewById(R.id.list_view);
        findViewById(R.id.tv_stock_count).setVisibility(View.GONE);

        et_skuCode = findViewById(R.id.et_skuCode);
        et_skuCode.setOnEditorActionListener(new QueryGoodsLocationActivity.OnActionListener());
    }

    @Override
    protected void initData() {
        super.initData();
        mAdapter = new GoodsLocationsAdapter(this);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void getScanResult(String scanResult) {
        super.getScanResult(scanResult);
        if (TextUtils.isEmpty(scanResult)) {
            ToastUtils.showShort(QueryGoodsLocationActivity.this, "扫码结果为空，请重试");
            return;
        }
        if (getCurrentWarehouse() == null) {
            ToastUtils.showShort(QueryGoodsLocationActivity.this, "当前仓库信息获取失败");
            return;
        }
        if (TextUtils.isEmpty(CommonUtil.skuCodeSplit(this, scanResult))) {
            SpeakUtils.speakWithToast(this, "商品条码截取结果为空，请检查输入和截图规则", false, false);
            return;
        }
        scanResult = CommonUtil.skuCodeSplit(this, scanResult);
        et_skuCode.setText(scanResult);

        queryLocationStockInfo(scanResult);
    }

    private void queryLocationStockInfo(String barcode) {
        showLoadingDialog();
        if (mIQueryGoodsLocation == null) {
            mIQueryGoodsLocation = new QueryGoodsLocationImpl();
        }
        mIQueryGoodsLocation.queryGoodsLocation(getCurrentWarehouse().getId(), barcode, new OnRequestCallback<JSONObject>() {
            @Override
            public void onFailedCallback(boolean isRequestCallback, final String errorMsg) {
                super.onFailedCallback(isRequestCallback, errorMsg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        initNoDataView();
                        ToastUtils.showLong(QueryGoodsLocationActivity.this, errorMsg);
                    }
                });
            }

            @Override
            public void onSuccessCallback(final JSONObject result, Object object) {
                super.onSuccessCallback(result, object);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        showView(result);
                    }
                });
            }
        });
    }

    private void initNoDataView() {
        mTvGoodsName.setText("商品名称：—");
        mTvSpecName.setText("规格名称：—");
        mTvSKUNum.setText("SKU 编码：—");
        mTvGoodsNum.setText("商品编码：—");
        mTvGoodsBarcode.setText("商品条码：—");
        mIvGoodsPic.setImageResource(R.mipmap.image_pic_default);
        mTvNoDataTips.setVisibility(View.VISIBLE);
        mListView.setVisibility(View.GONE);
    }

    private void showView(JSONObject data) {
        if (data != null) {
            mTvGoodsName.setText("商品名称：" + data.optString("itemName"));
            mTvSpecName.setText("规格名称：" + data.optString("specName"));
            mTvSKUNum.setText("SKU 编码：" + data.optString("skuCode"));
            mTvGoodsNum.setText("商品编码：" + data.optString("itemCode"));
            mTvGoodsBarcode.setText("商品条码：" + data.optString("itemBarcode"));
            GlideUtils.loadImage(this, data.optString("pictureUrl", ""), mIvGoodsPic);
            getWarehouseLocationData(data);
        } else {
            initNoDataView();
        }
    }

    private void getWarehouseLocationData(JSONObject data) {
        try {
            JSONArray array = data.getJSONArray("itemLocations");
            if (array != null && array.length() > 0) {
                List<WarehouseLocation> whLocationList = new ArrayList<>();
                for (int i = 0; i < array.length(); i++) {
                    WarehouseLocation whLocation = new WarehouseLocation();
                    JSONObject json = array.getJSONObject(i);
                    whLocation.setLocationId(json.optLong("locationId"));
                    whLocation.setLocationName(json.optString("locationName"));
                    whLocation.setAreaName(json.optString("areaName"));
                    whLocation.setAreaType(json.optInt("areaType"));
                    whLocation.setLaunchSort(json.optInt("launchSort"));

                    whLocationList.add(whLocation);
                }
                mTvNoDataTips.setVisibility(View.GONE);
                mListView.setVisibility(View.VISIBLE);
                mAdapter.setData(whLocationList);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mTvNoDataTips.setVisibility(View.VISIBLE);
        mListView.setVisibility(View.GONE);
    }

    class OnActionListener implements TextView.OnEditorActionListener {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                String input = v.getText().toString().trim();
                if (TextUtils.isEmpty(input)) {
                    ToastUtils.showShort(QueryGoodsLocationActivity.this, "扫码结果为空，请重试");
                    return true;
                }
                if (getCurrentWarehouse() == null) {
                    ToastUtils.showShort(QueryGoodsLocationActivity.this, "当前仓库信息获取失败");
                    return true;
                }
                String skuSplit = CommonUtil.skuCodeSplit(QueryGoodsLocationActivity.this, input);
                if (TextUtils.isEmpty(skuSplit)) {
                    SpeakUtils.speakWithToast(QueryGoodsLocationActivity.this, "商品条码截取结果为空，请检查输入和截图规则", false, false);
                    return true;
                }
                queryLocationStockInfo(skuSplit);
                return true;
            }
            return false;
        }
    }

    @Override
    public void changeWarehouse(Warehouse warehouse) {
        initNoDataView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
